package parser

import (
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/util"
	"github.com/sirupsen/logrus"
	"os"
)

func parseWrapperConfig(version string, flags config.Flags) (cfg *config.TFWrapperConfig, diags hcl.Diagnostics) {
	cfg = new(config.TFWrapperConfig)
	cfg.WorkingDir, _ = os.Getwd()
	cfg.TFWrapperVersion = version
	cfg.Stack = flags.Stack
	logrus.Debugf("Search wrapper config: %s", flags.GetConfigName())

	var err error
	if cfg.CurrentConfigPath, err = util.FindInParentFolder(cfg.WorkingDir, flags.GetConfigName()); err != nil {
		return nil, errors.Diagnostics("Not found", err)
	}
	logrus.Infof("found wrapper config: %s", cfg.CurrentConfigPath)

	cfg.WrapperConfigPath = cfg.CurrentConfigPath
	var hclFile *hcl.File
	if hclFile, diags = util.ParseHcl(cfg.CurrentConfigPath); diags.HasErrors() {
		return
	}

	if diags = evaluateConstraint(&cfg.Running, nil, flags, hclFile); util.HasErrors(diags) {
		return
	}

	if cfg.Functions, diags = parseFunctions(cfg.Running, hclFile); util.HasErrors(diags) {
		return
	}

	if cfg.Globals, diags = evaluateGlobalsBlock(cfg.Running, hclFile); util.HasErrors(diags) {
		return
	}

	if cfg.Stacks, diags = parseStacks(cfg.Running, hclFile); util.HasErrors(diags) {
		return
	}

	if cfg.Inputs, diags = evaluateInputsBlock(cfg.Running, hclFile); util.HasErrors(diags) {
		return
	}

	if cfg.Generators, diags = parseGenerator(cfg.Running, hclFile); util.HasErrors(diags) {
		return
	}

	if cfg.Terraform, diags = parseTerraform(cfg.Running, hclFile); util.HasErrors(diags) {
		return
	}

	return
}
